package ca.camosun.morsecode.nongui;


import java.util.HashMap;

import static ca.camosun.morsecode.nongui.MorseConstants.*;
import static ca.camosun.morsecode.nongui.MorseConstants.Index.*;
import static ca.camosun.morsecode.nongui.MorseConstants.Token.*;

import java.util.Map;


import ca.camosun.morsecode.nongui.MorseConstants.Timing;
import ca.camosun.morsecode.nongui.MorseConstants.Token;

import android.os.Vibrator;
import android.content.Context;

public class MorseVibrator {

	private Map<String, String> letterMap;
	private Vibrator mVibrator;
	private Timing timing;

	public MorseVibrator(Context inContext, Timing inTiming) {
		
		mVibrator = (Vibrator) inContext
				.getSystemService(Context.VIBRATOR_SERVICE);
		
		timing = inTiming;
		
		letterMap = new HashMap<String, String>();
		
		for(int i = 0; i < morseLetters.length; i++) {
			letterMap.put(morseLetters[i][LETTER.valueOf()], morseLetters[i][DOT_DASH.valueOf()]);
		}
	}
	
	public void vibrate(String message) {
		for(int i = 0; i < message.length(); i++) {
			vibrateSingleChar(message.charAt(i) + "");
			morseVibrate(SHORT_PAUSE, timing);
		}
	}
	
	public void vibrateSingleChar(String item) {
		
		if(item.equals(" ")) {
			morseVibrate(LONG_PAUSE, timing);
			return;
		}
		
		String dotDashes = letterMap.get(item);
		if(dotDashes == null) {
			return;
		}
		
		for(int i = 0; i < dotDashes.length(); i++) {
			
			switch(dotDashes.charAt(i)) {
			
			case '.':
				morseVibrate(DOT, timing);
				break;
				
			case '-':
				morseVibrate(DASH, timing);
			}
		}	
	}

	public void morseVibrate(Token symbol, Timing baseTime) {

		switch (symbol) {
			case DOT:
			case DASH:
				mVibrator.vibrate(symbol.getRelativeTime() * baseTime.valueOf());
				break;
				
			case SHORT_PAUSE:
			case LONG_PAUSE:
				try {
					Thread.sleep(symbol.getRelativeTime() * baseTime.valueOf());
				} catch (InterruptedException e) {
					System.out.println("Couldn't sleep. Error: " + e.getMessage());
				}
				break;
				
			default:
				break;
		}
	}
}
